package com.xlh.dto.courseTest;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.xlh.exception.common.GlobalException;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Comparator;
import java.util.List;

/**
 * @author zhr 2019/3/19
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class AnswerSheetDTO {
    // 题目id
    private Long id;
    // 题号
    private Integer orderNumber;
    // 题型
    private Integer type;
    // 答案
    private Object answer;
    private String htmlContent;
    // 得分
    private Integer score = 0;
    // 是否正确
    private Boolean right = false;
    // 是否正确
    private Boolean jz = false;
    public AnswerSheetDTO(Long id, Integer orderNumber, Integer type) {
        this.id = id;
        this.orderNumber = orderNumber;
        this.type = type;
        this.score = 0;
        this.right = false;
    }
    public AnswerSheetDTO(Long id, Integer orderNumber, Integer type,Boolean jz) {
        this.id = id;
        this.orderNumber = orderNumber;
        this.type = type;
        this.score = 0;
        this.right = false;
        this.jz = jz;
    }
    public static List<AnswerSheetDTO> parse(String content) {
        if (StringUtils.isBlank(content)) {
            return Lists.newArrayList();
        }
        List<AnswerSheetTypeDTO> answerSheetTypeList = JSONArray.parseArray(content, AnswerSheetTypeDTO.class);
        return parse(answerSheetTypeList);
    }

    public static List<AnswerSheetDTO> parse(List<AnswerSheetTypeDTO> typeList) {
        List<AnswerSheetDTO> result = Lists.newArrayList();
        if (CollectionUtils.isEmpty(typeList)) {
            return result;
        }
        typeList.forEach(dto -> result.addAll(dto.getAnswerSheetList()));
        result.sort(Comparator.comparing(AnswerSheetDTO::getOrderNumber));
        return result;
    }
    public static void parseOther(List<AnswerSheetTypeDTO> typeList) {
        List<AnswerSheetDTO> result = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(typeList)) {
            for (AnswerSheetTypeDTO answerSheetTypeDTO :typeList ) {
                if (answerSheetTypeDTO.getAnswerSheetList()!=null){
                    List<AnswerSheetDTO> answerSheetList = answerSheetTypeDTO.getAnswerSheetList();
                    for (int i = 0; i < answerSheetList.size(); i++) {

                        String s = answerSheetList.get(i).getAnswer()==null?"":answerSheetList.get(i).getAnswer().toString();
                        if (s.length()>20000){
                            throw new GlobalException("内容长度不能超过20000个字符");
                        }

                    }
                }
            }
        }
    }
}
